<template>
  <div class="app-container customer-div">

    <el-menu :default-active="listQuery.tab" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="my">我负责的</el-menu-item>
<!--      <el-menu-item index="all" v-if="isallSupplierContact">全部</el-menu-item>-->
    </el-menu>

    <div style="margin-top: 20px">
      <el-button
              size="small"
              @click="showDialog('add',null)"
              type="primary">
        新增联系人
      </el-button>
    </div>
    <div style="margin-top: 20px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="140px">
        <el-form-item label="供应商名称：">
          <el-select
                  clearable
                  v-model="listQuery.supplierId"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  :remote-method="remoteMethod3"
                  :loading="loading">
            <el-option
                    v-for="item in supplierList2"
                    :key="item.supplierId"
                    :label="item.supplierName"
                    :value="item.supplierId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人：">
          <el-input v-model="listQuery.contactName"></el-input>
        </el-form-item>
        <el-form-item label="手机号：">
            <el-input v-model="listQuery.contactMobile"></el-input>
        </el-form-item>
        <el-form-item label="创建时间：">
          <el-date-picker
                  :default-time="['00:00:00', '23:59:59']"
                  v-model="listQuery.createTime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="最近联系时间：">
          <el-date-picker
                  :default-time="['00:00:00', '23:59:59']"
                  v-model="listQuery.lastContactTime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建人：" v-if="listQuery.tab != 'my'">
          <el-select v-model="listQuery.createUserId" placeholder="请选择" clearable>
            <el-option
              v-for="item in userOptionList"
              :key="item.userId"
              :label="item.realName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--数据列表-->
    <div class="table-container">
      <el-table
        v-loading="listLoading"
        :data="list"
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column
                label="供应商名称"
                width="400">
            <template slot-scope="scope">
              <el-link @click="toDetail(scope.row)" type="primary">
                {{scope.row.supplierName}}
              </el-link>
            </template>
        </el-table-column>
        <el-table-column
          prop="contactName"
          label="联系人"
          align="center"
          width="100">
        </el-table-column>
        <el-table-column
          prop="contactMobile"
          label="联系人手机号"
          align="center"
          width="120">
        </el-table-column>
        <el-table-column
          align="center"
          prop="chargeGoodsList"
          label="负责产品"
          width="180">
        </el-table-column>
        <el-table-column
          label="职务"
          width="120"
          align="center">
          <template slot-scope="scope">
            {{scope.row.contactDuty}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="是否为主联系人"
          width="120">
          <template slot-scope="scope">
            {{scope.row.isMainContact== 1 ? '是' : '否'}}
          </template>
        </el-table-column>
        <el-table-column
          label="最近联系时间"
          width="150"
          align="center">
          <template slot-scope="scope">
            {{scope.row.lastContactTime}}
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          width="150"
          align="center">
          <template slot-scope="scope">
            {{scope.row.createTime}}
          </template>
        </el-table-column>
        <el-table-column
                label="创建人"
                width="120"
                align="center">
          <template slot-scope="scope">
            {{scope.row.createName}}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="showDialog('edit',scope.row)">编辑
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="delRow(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="count">
      </el-pagination>
    </div>

    <!--新增/编辑联系人-->
    <el-dialog
      :close-on-click-modal="false"
      :title="title2"
      :beforeClose="handleClose2"
      :visible.sync="dialogVisible2"
      width="600px">
      <el-form :model="contactForm" size="mini" label-width="120px" :rules="rules" ref="contactForm">
        <el-form-item label="供应商：" prop="supplierId">
          <el-select
            v-if="showDialogType=='add'"
            v-model="contactForm.supplierId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            :loading="loading">
            <el-option
              v-for="item in supplierList"
              :key="item.supplierId"
              :label="item.supplierName"
              :value="item.supplierId">
            </el-option>
          </el-select>
          <div v-else>{{contactForm.supplierName}}</div>
        </el-form-item>
        <el-form-item label="联系人：" prop="contactName">
          <el-input style="width:208px;" v-model="contactForm.contactName"></el-input>
        </el-form-item>
        <el-form-item label="联系人手机号：" prop="contactMobile">
          <el-input style="width:208px" v-model="contactForm.contactMobile"></el-input>
        </el-form-item>
        <el-form-item label="负责产品：">
          <el-select
                  multiple
                  clearable
                  v-model="contactForm.goodsKingIds"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  :remote-method="remoteMethod2"
                  :loading="loading2">
            <el-option
                    v-for="item in options"
                    :key="item.kingId"
                    :label="item.goodsSn"
                    :value="item.kingId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职务：">
          <el-input style="width:208px" v-model="contactForm.contactDuty"></el-input>
        </el-form-item>
        <el-form-item label="设为主联系人：">
          <el-checkbox v-model="contactForm.isMainContact">是</el-checkbox>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
    import { delTrackingInfo,getUserOption,supplierList} from '@/api/partner'
    import {supplierListApi,goodsList,supplierContactList,supplierContactEdit,supplierContactDel} from '@/api/company'
    import {formatDate} from '@/utils/date';
    import store from '@/store'
    import { mapGetters } from 'vuex'
    const defaultContactForm = {
      contactId:0,
      supplierId : '',  //供应商ID
      contactName : "", //联系人姓名
      contactMobile : "", //联系人手机号
      contactDuty : "", //职务
      isMainContact: 0 ,//是否主联系人
      goodsKingIds:[],
    };
    const defaultListQuery={
      pageNum: 1,
      pageSize: 10,
      supplierId:'',
      supplierName:'',
      contactName:'',
      createTime:null,
      createUserId:'',
      contactMobile:'',
      lastContactTime:null,
      tab:'my'
    };
    export default {
        name: "index",
        data(){
            return{
                roles:store.getters.roles ? store.getters.roles : [],
                listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
                list:[],
                count:0,
                listLoading:false,
                dialogVisible2:false,
                title2:'',
                btnLoading2:false,
                contactForm:JSON.parse(JSON.stringify(defaultContactForm)),
                rules:{
                  supplierId:[{required: true, message: '请选择供应商', trigger: 'change'},],
                  contactName:[{required: true, message: '请输入联系人姓名', trigger: 'blur'},],
                  contactMobile:[{required: true, message: '请输入联系人手机号', trigger: 'blur'},],
                },
                loading:false,
                supplierList:[],
                userOptionList:[],
                showDialogType:'',
                options:[],
                loading2:false,
              supplierList2:[],
            }
        },
        computed: {
          ...mapGetters([
            'name',
            'mobile',
            'userId'
          ]),
            isallSupplierContact(){
                if(this.roles.indexOf("allSupplierContact") != -1){
                    return true
                }else{
                    return false
                }
            },


        },
        created() {
            this.getListData();
            this.getUserOptionList();
        },
        filters: {
            formatTime(time) {
                let date = new Date(time);
                return formatDate(date, 'yyyy-MM-dd')
            },
        },
        methods:{
            //去详情页
            toDetail(item){
              let routeData = this.$router.resolve({name:'supplierInfo',query:{id:item.supplierId}});
              window.open(routeData.href);
            },
            /**
             * 切换选择状态
             */
            handleSelect(key, keyPath){
                this.listQuery.tab = key;
                this.handleSearchList();
            },
            //获取员工下拉选项
            getUserOptionList(){
                getUserOption().then((res)=>{
                    this.userOptionList = res;
                })
            },


            //获取供应商列表
            remoteMethod(query) {
                if(query && query!= ''){
                    this.loading = true;
                  //获取供应产列表
                  supplierList({supplierName:query}).then(response => {
                    this.supplierList = response;
                    this.loading = false;
                  }).catch(()=>{
                    this.loading = false;
                  });

                }
            },
          //获取供应商列表
          remoteMethod3(query) {
            if(query && query!= ''){
              this.loading3 = true;
              //获取供应产列表
              supplierListApi({tab:this.listQuery.tab,supplierName:query,pageNum:1,pageSize:1000}).then(response => {
                this.supplierList2 = response.list;
                this.loading3 = false;
              }).catch(()=>{
                this.loading3 = false;
              });

            }
          },
          //获取商品列表
          remoteMethod2(query) {
            if (query !== '') {
              this.loading2 = true;
              this.loading2 = false;
              goodsList({keywords:query}).then((res)=>{
                this.options = res.list;
              }).catch(()=>{
                this.loading2 = false;
              });
            } else {
              this.options = [];
            }
          },

            handleSearchList(){
                this.listQuery.pageNum = 1;
                this.getListData();
            },
            //获取列表
            getListData(){
                this.listLoading = true;
                let data = JSON.parse(JSON.stringify(this.listQuery));
              supplierContactList(data).then((res)=>{
                    this.list = res.list;
                    this.count = res.count;
                    this.listLoading = false;
                }).catch(()=>{
                    this.listLoading = false;
                })
            },

            handleSizeChange(val){
                this.listQuery.pageNum = 1;
                this.listQuery.pageSize = val;
                this.getListData();
            },
          handleCurrentChange(val){
                this.listQuery.pageNum = val;
                this.getListData();
            },


            //删除记录
            delRow(item){
                  this.$confirm('确定删除这条记录?', '提示', {
                      confirmButtonText: '确定',
                      cancelButtonText: '取消',
                      type: 'warning'
                  }).then(() => {
                    supplierContactDel({contactId:item.contactId}).then(()=>{
                          this.getListData();
                          this.$message({
                              type: 'success',
                              message: '删除成功!'
                          });
                      });
                  }).catch(() => {
                      this.$message({
                          type: 'info',
                          message: '已取消删除'
                      });
                  });
              },

            //显示新增/编辑
          showDialog(type,item){
                this.title2 = type == 'add' ? '新增联系人' : '编辑联系人';
                this.showDialogType = type
                this.dialogVisible2 = true;
                if(type=='add'){
                    this.options=[];
                    this.contactForm = JSON.parse(JSON.stringify(defaultContactForm));
                }else{
                    this.contactForm.contactId = item.contactId;
                    this.contactForm.supplierId = item.supplierId;
                    this.contactForm.supplierName = item.supplierName;
                    this.contactForm.contactName = item.contactName;
                    this.contactForm.contactMobile = item.contactMobile;
                    this.contactForm.contactDuty = item.contactDuty;
                    this.contactForm.isMainContact = item.isMainContact==1 ? true: false;
                    this.contactForm.goodsKingIds = item.goodsKingIds;
                    this.options=[];
                    let goodsName = item.chargeGoodsList.split(',');
                    item.goodsKingIds.forEach((el,index)=>{
                      this.options.push({kingId:el,goodsSn:goodsName[index]})
                    })
                }
            },

            //关闭弹窗
            handleClose2(){
                this.$refs.contactForm.clearValidate();
                this.dialogVisible2 = false;
                this.btnLoading2 = false;
                this.supplierList = [];
            },

            //提交联系人
            handleConfirm2(){
                this.$refs.contactForm.validate((valid) => {
                    if (valid) {
                        this.btnLoading2 = true;
                        let data = {};
                        data.contactId = this.showDialogType == 'add' ? 0 : this.contactForm.contactId;
                        data.supplierId = this.contactForm.supplierId;
                        data.contactName = this.contactForm.contactName;
                        data.contactMobile = this.contactForm.contactMobile;
                        data.contactDuty = this.contactForm.contactDuty;
                        data.goodsKingIds = this.contactForm.goodsKingIds;
                        data.isMainContact = this.contactForm.isMainContact ? 1 :0;
                        supplierContactEdit(data).then((res)=>{
                            this.btnLoading2 = false;
                            this.handleClose2();
                            this.getListData();
                        })
                    }
                })
            },
        },
    }
</script>

<style scoped lang="scss">
  .avatar-uploader{
    margin-bottom:10px;
    display: inline-block;
    width:80px;
    height:80px;
    border:1px solid #DCDFE6;
    text-align: center;
    line-height: 80px;
  }
</style>
